import { useEffect, useState } from "react";
import axios from '../utils/axios';
import { toast } from "sonner";
import { useNavigate } from 'react-router-dom';

const HospitalManage = () => {
  // const medicalType = 2;
  const statusMap = {
    "-1": '待处理',
    "0": '已审批',
    "1": '已拒绝'
  }

  const [records, setRecords] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(0);
  // const [recordsCount, setRecordsCount] = useState(0);
  const [recordType, setRecordType] = useState(-1);
  const [searchTerm, setSearchTerm] = useState("");
  const [showNotifications, setShowNotifications] = useState(false);

  const recordsPerPage = 5;

  const navigate = useNavigate();

  const fetchRecords = async (page: number) => {
    try {
      // const count = await axios.get('/api/v1/medical-records/count');
      // setRecordsCount(count.data.count);

      // 添加身份证筛选参数
      const response = await axios.get(`/api/v1/medical-records/fetch`, {
        params: {
          page,
          size: recordsPerPage,
          filter: recordType,
          searchTerm: searchTerm,
          type: 'hospital'
        }
      });

      console.log('获取的记录:', response.data.records);

      setRecords(response.data.records);
      setTotalPages(Number(response.data.pagination.totalPages));
      setLoading(false);
    } catch (error) {
      console.error('获取医疗记录失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSignature = async (recordId: number, approved: boolean) => {
    try {
      const response = await axios.post(`/api/v1/medical-records/signature`, {
        recordId,
        approved
      });

      console.log("签名返回的结果: ", response.data);

      if (response.data.success && response.data.status === approved) {
        toast.success("操作成功");
        fetchRecords(currentPage); // 刷新数据
      } else {
        toast.error('操作失败，操作结果不一致');
      }
    } catch (error) {
      toast.error('内部错误');
    }
  };

  const handleRefresh = () => {
    fetchRecords(currentPage);
    toast.success("刷新成功");
  }

  useEffect(() => {
    fetchRecords(currentPage);
  }, [currentPage, recordType]);

  // const handleSearch = () => {
  //   fetchRecords(1);
  // }

  // 搜索过滤
  // const filteredRecords = records.filter(record =>
  //   record.patientName.toLowerCase().includes(searchTerm.toLowerCase()) ||
  //   record.idNumber.includes(searchTerm)
  // );

  // const filteredRecords = records;

  // 分页计算
  // const indexOfLastRecord = currentPage * recordsPerPage;
  // const indexOfFirstRecord = indexOfLastRecord - recordsPerPage;
  const currentRecords = records;
  // const currentRecords = records;\
  // console.log(searchTerm, filteredRecords, indexOfFirstRecord, indexOfLastRecord, currentRecords);

  if (loading) return <div>加载中...</div>;

  return (
    <div>
      <h2 className="mb-4 text-xl font-bold">医院审批</h2>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
        <div className="rounded-md border border-gray-200 p-4 shadow-sm">
          <h3 className="mb-2 text-lg font-medium">待审批申请</h3>
          <p className="text-3xl font-bold text-[#673AB7]">
            {records.filter(r => r.status === -1).length}
          </p>
        </div>
        <div className="rounded-md border border-gray-200 p-4 shadow-sm">
          <h3 className="mb-2 text-lg font-medium">已处理申请</h3>
          <p className="text-3xl font-bold text-[#673AB7]">
            {records.filter(r => r.medicalType === 1).length}
          </p>
        </div>
      </div>

      <div className="my-6 flex items-center justify-between">
        <div className="flex items-center">
          <div className="relative w-64">
            <input
              type="text"
              placeholder="输入身份证号搜索..."
              className="w-full rounded-md border border-gray-300 px-4 py-2 pl-10 focus:border-[#673AB7] focus:outline-none"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && fetchRecords(1)}
            />
            <i className="fa-solid fa-id-card absolute left-3 top-3 text-gray-400"></i>
          </div>
          <button
            onClick={() => {
              fetchRecords(1);
              if (searchTerm) {
                setSearchTerm(searchTerm);
              }
            }}
            className="ml-2 flex items-center rounded-md bg-[#673AB7] px-4 py-2 text-white hover:bg-[#5E35B1]"
          >
            <i className="fa-solid fa-magnifying-glass mr-2"></i>搜索
          </button>
        </div>
        <button
          onClick={handleRefresh}
          className="ml-2 flex items-center rounded-md bg-[#673AB7] px-4 py-2 text-white hover:bg-[#5E35B1]"
        >
          <i className="fa-solid fa-rotate-right mr-2"></i>刷新
        </button>
      </div>

      {/* 表格区域 */}
      <div className="mt-6 space-y-6">
        <div className="border-b border-gray-200">
          <nav className="-mb-px flex space-x-8">
            <button
              onClick={() => {
                setRecordType(-1);
                setCurrentPage(1);
              }}
              className={`whitespace-nowrap border-b-2 px-1 py-4 text-sm font-medium ${recordType === -1 ? 'border-[#673AB7] text-[#673AB7]' : 'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700'
                }`}
            >
              待处理
            </button>
            <button
              onClick={() => {
                setRecordType(0);
                setCurrentPage(1);
              }}
              className={`whitespace-nowrap border-b-2 px-1 py-4 text-sm font-medium ${recordType === 0 ? 'border-[#673AB7] text-[#673AB7]' : 'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700'
                }`}
            >
              已审批
            </button>
            <button
              onClick={() => {
                setRecordType(1);
                setCurrentPage(1);
              }}
              className={`whitespace-nowrap border-b-2 px-1 py-4 text-sm font-medium ${recordType === 1 ? 'border-[#673AB7] text-[#673AB7]' : 'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700'
                }`}
            >
              已拒绝
            </button>
          </nav>
        </div>

        <div className="overflow-hidden rounded-md border border-gray-200 shadow-sm">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">姓名</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">身份证号</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">申请日期</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">医疗类型</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">状态</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">操作</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200 bg-white">
              {currentRecords.map((record) => (
                <tr key={record.id}>
                  <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                    {record.patientName}
                  </td>
                  <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                    {record.idNumber}
                  </td>
                  <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                    {record.date}
                  </td>
                  <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                    {['门诊', '住院', '检查', '手术'][record.medicalType]}
                  </td>
                  <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                    {statusMap[record.status.toString() as keyof typeof statusMap]}
                  </td>
                  <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                    <button
                      className="mr-2 rounded-md bg-blue-500 px-3 py-1 text-xs text-white hover:bg-blue-600"
                      onClick={() => {
                        navigate(`/record/${record.id}`);
                      }}
                    >
                      查看详情
                    </button>
                    {recordType === -1 && (
                      <>
                        <button
                          className="mr-2 rounded-md bg-green-500 px-3 py-1 text-xs text-white hover:bg-green-600"
                          onClick={() => handleSignature(record.id, true)}
                        >
                          同意
                        </button>
                        <button
                          className="rounded-md bg-red-500 px-3 py-1 text-xs text-white hover:bg-red-600"
                          onClick={() => handleSignature(record.id, false)}
                        >
                          拒绝
                        </button>
                      </>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* 分页控件 */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between">
            <button
              onClick={() => setCurrentPage(p => Math.max(p - 1, 1))}
              disabled={currentPage === 1}
              className="rounded-md border border-gray-300 px-4 py-2 disabled:opacity-50"
            >
              上一页
            </button>
            <span>
              第 {currentPage} 页 / 共 {totalPages} 页
            </span>
            <button
              onClick={() => setCurrentPage(p => Math.min(p + 1, totalPages))}
              disabled={currentPage === totalPages}
              className="rounded-md border border-gray-300 px-4 py-2 disabled:opacity-50"
            >
              下一页
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default HospitalManage;